﻿namespace KLF.Lib.Browser
{
    #region Using Statements

    using System;
    using System.Linq;
    using System.Collections.Generic;

    using KLF.Lib.Browser.DOM.HTML;
    using KLF.Lib.Browser.DOM.CSS.SAC.Selectors;
    using KLF.Lib.Browser.DOM;

    #endregion

    public class FormWrapper
    {
        #region Constructors

        internal FormWrapper(HTMLFormElement _form)
        {
            Form = _form;
        }

        #endregion

        #region Attributes

        private HTMLFormElement Form { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="selector"></param>
        /// <returns></returns>
        public IEnumerable<HTMLOptionElement> Options(Selector selector)
        {
            HTMLSelectElement s = (HTMLSelectElement)Form.Owner
                .Elements
                .DefaultIfEmpty(null)
                .Cast<HTMLSelectElement>()
                .FirstOrDefault(e => (e is HTMLSelectElement) && selector.Matches(e));

            return s != null ? s.Options : null;
        }

        #endregion

        #region Methods

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public FormWrapper Reset()
        {
            if (Form != null)
                Form.reset();

            return this;
        }

        /// <summary>
        /// Sets a single form value.
        /// </summary>
        /// <param name="key">The name of the control value to set.</param>
        /// <param name="value">The value to associate with the control.</param>
        /// <returns>Reference to th FormWrapper object (for chaining).</returns>
        public FormWrapper SetValue(string key, string value)
        {
            NodeList list = Form.querySelectorAll(Find.ByName(key));

            if (list == null || list.length == 0)
                throw new ArgumentException("Could not locate item specified.");

            for (int i = 0; i < list.length; i++)
            {
                HTMLControlBase input = list[i] as HTMLControlBase;
                if (input != null)
                    input.SimulateInput(value);
            }
            return this;
        }

        /// <summary>
        /// Submits the form.
        /// </summary>
        /// <returns></returns>
        public FormWrapper Submit()
        {
            Form.submit();
            return this;
        }

        #endregion
    }
}
